<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>进出扫码记录</title>
    <link rel="stylesheet" href="">
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cozmo.github.io/jsQR/jsQR.js"></script>
</head>
<body>
<!--
客观的情况下，下面这些元素已经得到了各大浏览器厂商的支持，
客户端支持视频/摄像机，为了证明
所涉及的元素，它们是用hmtl标签(而不是JavaScript)创建的
-->
<video id="video" width="640" height="480" autoplay></video>
<button id="snap"  onclick="start()">开始工作</button>
<canvas id="canvas" width="640" height="480"></canvas>
<div>
    <ul id="result">
    </ul>
    <audio src="" id="sound"></audio>
</div>
</body>
<script type="text/javascript">
    function sleep(d){
        for(var t = Date.now();Date.now() - t <= d;);
    }
    function  draw() {
        context.drawImage(video, 0, 0, 640, 480);
        base64ToqR();
    }
    function start() {
        $("#snap").hide();
        //每2秒调用一次draw
        setInterval(draw, 2000);
    }
    var flag = false;
    var video = document.getElementById('video');
    // 得到摄像头api
    if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        // 如果我们想要立即显示拍照，请设置 { video: true }
        navigator.mediaDevices.getUserMedia({ video: true }).then(
            function(stream) {
                //video.src = window.URL.createObjectURL(stream);
                video.srcObject = stream;
                video.play();
            });
    }
    // 用于拍摄快照的元素,添加canvas里面
    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');
    var video = document.getElementById('video');
</script>
<script type="text/javascript">
    $("body").append('<canvas id="qrcanvas" style="display:none;"></canvas>')
    $("#canvas").change(function (e) {
        var file = e.target.files[0];
        if(window.FileReader) {
            var fr = new FileReader();
            fr.readAsDataURL(file);
            fr.onloadend = function(e) {
                var base64Data = e.target.result;
                base64ToqR(base64Data)
            }
        }
    })
    function base64ToqR() {
        var ctx = canvas.getContext("2d");
            var imageData = ctx.getImageData(0, 0, 640, 480);
            const code = jsQR(imageData.data, imageData.width, imageData.height, {
                inversionAttempts: "dontInvert",
            });
            if(code){
                showCode(code.data)
            }else{
                sleep(1000)
            }
    }
    var time;
    function showCode(code){
        var audio = $("#sound")[0];
        audio.src="/sendQRcode?BrowserCode="+code;
        audio.play();
       // time = Date.now();
        //code = code + time
        //$("#result").append("<li>"+code+"</li>")
    }

</script>
</html>